package feces.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import feces.Config;

/**
 * 编码过滤器
 *
 * @author Bromine0x23
 */
public class EncodingFilter implements Filter {
	
	/**
	 * 附加于请求指明编码的参数键
	 */
	public static final String ENCODING_KEY = "utf8";

	/**
	 * 附加于请求指明编码的参数值
	 */
	public static final String ENCODING_ENABLE = "√";

	@Override
	public void destroy() {
		// do nothing
	}

	/**
	 * 设置请求编码和响应编码
	 */
	@Override
	public void doFilter(
		ServletRequest request,
		ServletResponse response,
		FilterChain chain
	) throws IOException, ServletException {
		if (request.getCharacterEncoding() == null) {
			String utf8 = request.getParameter(ENCODING_KEY);
			if (utf8 == null || utf8.equals(ENCODING_ENABLE)) {
				request.setCharacterEncoding(Config.ENCODING);
			}
		}
		response.setCharacterEncoding(Config.ENCODING);
		chain.doFilter(request, response);
	}

	@Override
	public void init(
		FilterConfig config
	) throws ServletException {
		// do nothing
	}

}
